import { $portal } from 'src/boot/$portal'
import website from 'src/const/website'
import store from 'src/store'
import md5 from 'js-md5';

const post2Portal = (param) => {
  let headers = {};
  // 自定义表头部分  用于扩展
  // let ContentType = 'application/json; charset=utf-8'
  let ContentType = 'application/x-www-form-urlencoded'
  if (param.headers) {
    headers = param.headers;
    if (param.headers.hasOwnProperty('ContentType')) {
      ContentType = param.headers.ContentType
      delete headers.ContentType
    }
    delete param.headers
  }
  // 预留-原portal正常post传值
  let dataStr = '' // 数据拼接字符串
  if (typeof param.methods === 'undefined') {
    param.methods = 'POST'
  }


  let token = store.getters.access_token
  let signkey = store.getters.signKey

  param.data = Object.assign(param.data, {
    deviceType: 3,
    version: '1.0.0',
    timestamp: new Date().format('yyyyMMddhhmmss'),
    nonce: Date.parse(new Date()) / 1000,
    token: token
  });

  let pcKey = 'w8pUMjTPN7AcctmE76zmedraidWx1nbO'
  let sign = ''
  Object.keys(param.data).sort().forEach(key => {
    if(param.data[key]) {
      sign += encodeURIComponent(key) + '=' + encodeURIComponent(param.data[key]) + '&'
    }
  })
  sign = sign.substr(0, sign.lastIndexOf('&'))
  sign = sign +  `|hx_app|${pcKey}|hx_app_shop|` + signkey

  param.data.sign = md5(sign)

  if (param.methods.toLocaleUpperCase() === 'POST' && ContentType === 'application/x-www-form-urlencoded') {
    Object.keys(param.data).forEach(key => {
      dataStr += encodeURIComponent(key) + '=' + encodeURIComponent(param.data[key]) + '&'
    })
    if (dataStr !== '') {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
      // dataStr += `_t= ${Date.parse(new Date()) / 1000}`
    }

    // dataStr =  new URLSearchParams();
    // Object.keys(param.data).forEach(key => {
    //   dataStr.append(key, param.data[key])
    // })

  } else {
    // json 走这里
    dataStr = param.data
  }

  let domain = website.baseURL

  return new Promise(
    function (resolve, reject) {
      $portal({
        baseURL: domain,
        url: param.api,
        method: param.methods || 'post',
        data: param.methods === 'POST' || param.methods === 'PUT' || param.methods === 'PATCH' || param.methods === 'DELETE' ? dataStr : null,
        params: param.methods === 'GET' ? dataStr : null,
        // data: dataStr,
        headers: {
          'Content-Type': ContentType,
          'X-Requested-With': 'XMLHttpRequest',
          'X-URL-PATH': location.pathname,
          'token': token,
          ...headers
        }
      }).then(
        success => {
          if (website.isdevelop) {
            resolve(success.data);
          } else {
            if (success.code !== 200) {
              reject(success);
            } else {
              if (success.hasOwnProperty('data')) {
                success.data = success.data || {}
                if (typeof success.data === 'object' && !Array.isArray(success.data)) {
                  success.data.message = success.data.message || success.message;
                }
                resolve(success.data)
              } else {
                resolve(success)
              }
            }
          }
        },
        error => {
          reject(error);
        }
      );
    }
  )
};

export default post2Portal
